package com.byfan.barter.controller;

import com.byfan.barter.utils.Message;
import com.byfan.barter.utils.MessageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

/**
 * @Author: FBY
 * @Description
 * @Version 1.0
 * @Date: 2021/5/17 11:34
 */
@Api(description = "其他接口")
@RestController
@RequestMapping("/other")
public class OtherController {

    private String DIR = "src/main/resources/static";

    @ApiOperation("小程序上传图片")
    @RequestMapping(value = "/uploadImg",method = RequestMethod.POST)
    public Message uploadImg(HttpServletRequest request) {
        String imgName = "";
        //获取文件请求
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;

        Iterator<String> iterator = req.getFileNames();
        try {
            while (iterator.hasNext()) {
                MultipartFile multipartFile = req.getFile(iterator.next());

                File file = new File(DIR);
                if (!file.exists()) {
                    file.mkdir();
                }
                long dateTime = new Date().getTime();
                //取得图片的格式后缀
                String originalFilename = multipartFile.getOriginalFilename();
                String picType = originalFilename.substring(originalFilename.lastIndexOf("."));
                //拼接图片名称 时间戳+uuid+.jpg
                imgName = dateTime + picType;
                //写入本地
                multipartFile.transferTo(new File(DIR, imgName));
            }

        } catch (IOException e) {
            e.printStackTrace();
            return MessageUtil.error("上传失败");
        }
        return MessageUtil.success("上传成功", imgName);
    }
}
